<script setup>
import {ref} from 'vue'
import {Edit, Delete} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus"

import {
    articleCategoryListService,
    articleListService,
    articleAddService,
    articleUpdateService,
    articleDeleteService
} from "@/api/article.js"
import ArticleDrawer from '@/views/article/ArticleDrawer.vue'

// 文章分类数据
const categories = ref([])
// 文章列表数据
const articles = ref([])
// 分页数据
const pageNum = ref(1)
const total = ref(0)
const pageSize = ref(5)
// 搜索条件
const categoryId = ref('')
const state = ref('')
// 新增搜索关键字
const keyword = ref('')

// 抽屉控制
const visibleDrawer = ref(false)
const title = ref("添加日记")
const articleModel = ref({
    title: '',
    categoryId: '',
    coverImg: '',
    content: '',
    state: '',
    id: null
})

// 获取分类列表
const articleCategoryList = async () => {
    const result = await articleCategoryListService()
    categories.value = result.data
}

// 获取文章列表
const articleList = async () => {
    const params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        categoryId: categoryId.value || null,
        state: state.value || null,
        keyword: keyword.value || null // 添加搜索关键字参数
    }
    const result = await articleListService(params)
    total.value = result.data.total
    articles.value = result.data.items

    // 关联分类名称
    articles.value.forEach(article => {
        const category = categories.value.find(c => c.id === article.categoryId)
        article.categoryName = category?.categoryName || '未知分类'
    })
}

// 分页处理
const onSizeChange = (size) => {
    pageSize.value = size
    articleList()
}

const onCurrentChange = (num) => {
    pageNum.value = num
    articleList()
}

// 显示编辑弹窗
const showDialog = (row) => {
    title.value = '编辑日记'
    articleModel.value = {
        ...row,
        id: row.id
    }
    visibleDrawer.value = true
}

// 添加文章
const addArticle = async (clickState) => {
    try {
        articleModel.value.state = clickState
        const result = await articleAddService(articleModel.value)
        ElMessage.success(result.msg || '添加成功')
        visibleDrawer.value = false
        await articleList()
        window.location.reload()
    } catch (error) {
        ElMessage.error('添加日记失败')
        console.error('添加日记失败:', error)
    }
}

// 更新文章
const updateArticle = async (clickState) => {
    try {
        //把发布状态赋值给数据模型
        articleModel.value.state = clickState
        //调用接口
        const result = await articleUpdateService(articleModel.value)
        ElMessage.success(result.msg || '修改成功')
        visibleDrawer.value = false
        //调用获取所有分类的函数
        await articleList()
        window.location.reload()
    } catch (error) {
        ElMessage.error('更新日记失败')
        console.error('更新日记失败：', error.msg)
    }
}

// 取消操作
const drawerCancel = () => {
    ElMessageBox.confirm('确定要关闭吗？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        visibleDrawer.value = false
        window.location.reload()
    }).catch(() => {
        ElMessage({type: 'info', message: '取消操作'})
    })
}

// 初始化数据
articleCategoryList()
articleList()

const deleteArticle = (row) => {
    //提示用户，确认框
    ElMessageBox.confirm(
        '你确认要删除该日记信息吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            try {
                //调用接口
                let result = await articleDeleteService(row.id);
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                //刷新列表
                articleList();
            } catch (error) {
                ElMessage({
                    type: 'error',
                    message: '删除失败，请稍后重试',
                })
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>日记管理</span>
                <div class="extra">
                    <el-button type="primary" @click="title = '添加日记'; visibleDrawer = true">
                        添加日记
                    </el-button>
                </div>
            </div>
        </template>

        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="日记分类：">
                <el-select v-model="categoryId" placeholder="请选择" style="width: 200px;">
                    <el-option
                        v-for="c in categories"
                        :key="c.id"
                        :label="c.categoryName"
                        :value="c.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="发布状态：">
                <el-select v-model="state" placeholder="请选择" style="width: 200px;">
                    <el-option label="已发布" value="已发布"/>
                    <el-option label="草稿" value="草稿"/>
                </el-select>
            </el-form-item>
            <!-- 新增搜索关键字输入框 -->
            <el-form-item label="关键字：">
                <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="articleList">搜索</el-button>
                <el-button @click="categoryId = ''; state = '';keyword=''">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 文章表格 -->
        <el-table :data="articles" style="width: 100%">
            <el-table-column label="日记标题" prop="title" width="400"/>
            <el-table-column label="分类" prop="categoryName"/>
            <el-table-column label="发表时间" prop="createTime"/>
            <el-table-column label="状态" prop="state"/>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"/>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteArticle(row)"/>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="暂无数据"/>
            </template>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[3, 5, 10, 15]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
        />

        <!-- 抽屉组件 -->
        <ArticleDrawer
            v-model:visible="visibleDrawer"
            :title="title"
            :categories="categories"
            :article-model="articleModel"
            @addArticle="addArticle"
            @updateArticle="updateArticle"
            @cancel="drawerCancel"
        />
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
}
</style>